package com.example.wifi_direct.utils

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import java.util.concurrent.atomic.AtomicInteger
import org.jetbrains.anko.db.ManagedSQLiteOpenHelper


class UserDataBase (var context: Context):ManagedSQLiteOpenHelper(context,"UserDataBase.db",null){

    companion object{
        var DB_NAME:String="UserDataBase.db"

        var TABLE_NAME="User_info"

        private var instance: UserDataBase?=null

        @Synchronized
        fun getInstance(ctx: Context):UserDataBase{
            if (instance==null){
                instance= UserDataBase(ctx.applicationContext)
            }
            return instance !!
        }
    }

    override fun onCreate(db: SQLiteDatabase?) {
        val drop_sql="DROP TABLE IF EXISTS $TABLE_NAME;"
        db?.execSQL(drop_sql)
        val create_sql="CREATE TABLE IF NOT EXISTS $TABLE_NAME("+
                "userName CHAR(45) PRIMARY KEY NOT NULL,"+
                "passWord CHAR(45) NOT NULL," + "prestige INT NULL,"+
                "gold INT NULL,"+"status INT NULL);"
        db?.execSQL(create_sql)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }
    //删除数据
    fun delete(condition:String):Int{
        var count=0
        use {
            count=delete(TABLE_NAME,condition,null)
        }
        return count
    }

    //添加数据
    fun insert(info:UserData):String{
        var result:String=""
        var  tempArray:List<UserData>
        if (info.userName!=null){
            val condition ="userName = '${info.userName}'"
            tempArray=query(condition)
            Log.d("query result is",tempArray.toString())
            if (tempArray.isNotEmpty()){
                result= tempArray[0].userName!!
                Log.d("update","update id is $result")
//                info.userName=result
                //update(info,condition)
                result=""
                return result
            }
        }
        val cv = ContentValues()
        cv.put("userName",info.userName)
        cv.put("passWord",info.passWord)
        use {
            result=insert(TABLE_NAME,"",cv).toString()
        }
        return result
    }
    //检查账号密码
    fun check(info:UserData):String{
        var result:String="123"
        var  tempArray:List<UserData>
        if (info.userName!=null){
            val condition ="userName = '${info.userName}'"
            tempArray=query(condition)
            Log.e("query result is",tempArray.toString())
            if (tempArray.isNotEmpty()){

                result= tempArray[0].userName!!
                //Log.d("update","update id is $result")
//                info.userName=result
                //update(info,condition)
                if(info.passWord==tempArray[0].passWord) {
                    updateStatus(info, condition)
                    result = ""
                    return result
                }
            }
        }
//        val cv = ContentValues()
//        cv.put("userName",info.userName)
//        cv.put("passWord",info.passWord)
//        use {
//            result=insert(TABLE_NAME,"",cv).toString()
//        }

        return result
    }
    //获取登录状态
    fun getWhoLogin(): List<UserData> {

        var tempArray: List<UserData>
            val condition = "status = 1"
            tempArray = query(condition)
            Log.e("query result is", tempArray.toString())

        return tempArray


    }

    //更新数据
    @JvmOverloads
    fun update(info: UserData,condition: String="userName=${info.userName}"):Int{
        val cv = ContentValues()
        cv.put("userName",info.userName)
        cv.put("passWord",info.passWord)
        var count=0
        use {
            count=update(TABLE_NAME,cv,condition,null)
        }
        return count
    }

    fun updateStatus(info: UserData,condition: String="userName=${info.userName}"):Int{
        val cv = ContentValues()
        cv.put("userName",info.userName)
        cv.put("status", 1)
        var count=0
        use {
            count=update(TABLE_NAME,cv,condition,null)
        }
        return count
    }
    fun OutofLog(): String? {
        var tempArray: List<UserData>
        val condition = "status = 1"
        tempArray = query(condition)
        val cv = ContentValues()
        cv.put("status", 0)
        var count=0
        use {
            count=update(TABLE_NAME,cv,condition,null)
        }
        return tempArray[0].userName
    }
    fun changeGold(): String? {
        var tempArray: List<UserData>
        val condition = "status = 1"
        tempArray = query(condition)
        var gold= tempArray[0].gold?.plus(1)
        val cv = ContentValues()
        cv.put("gold", gold)
        var count=0
        use {
            count=update(TABLE_NAME,cv,condition,null)
        }
        return tempArray[0].userName
    }
    //更改声望
    fun changePrestige(): String? {
        var tempArray: List<UserData>
        val condition = "status = 1"
        tempArray = query(condition)
        if(tempArray.isNotEmpty()) {
            var prestige = tempArray[0].prestige?.plus(1)
            val cv = ContentValues()
            cv.put("prestige", prestige)
            var count = 0
            use {
                count = update(TABLE_NAME, cv, condition, null)
            }
            return tempArray[0].userName
        }
        else return null
    }


    fun query(condition: String):List<UserData>{
        val sql= "select userName,passWord,prestige,gold,status from $TABLE_NAME where $condition;"
        Log.e("sql is",sql)
        var infoArray= mutableListOf<UserData>()
        use {
            val cursor = rawQuery(sql,null)
            if (cursor.moveToFirst()){
                while (true){
                    val info=UserData()
                    info.userName=cursor.getString(0)
                    info.passWord=cursor.getString(1)
                    info.prestige=cursor.getInt(2)
                    info.gold=cursor.getInt(3)
                    info.status=cursor.getInt(4)
                    infoArray.add(info)
                    if (cursor.isLast){
                        break;
                    }
                    cursor.moveToNext()
                }
            }
            cursor.close()
        }

        return infoArray
    }

    fun queryAll():List<UserData> =query("1=1")
}
